/**
 *
 */
package org.msfj.common.base;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 控制器基类
 * @Author: like
 * @Date: 2017-10-20 15:49
 * @Version: 1.0
 * @Created in idea by autoCode
 */
public class BaseController<Service extends BaseService, Model extends BaseModel> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());




    /**
     * 通过spring的RequestContextHolder获取request
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 通过spirng的RequestContextHolder获取response
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return response;
    }

    /**
     * 返回访问者的ip地址
     *
     * @return
     */
    public String getIpAddr() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 验证验证码
     *
     * @param verifyCode
     * @param ifTrueDelete
     * @return
     */
    public boolean validateVerifyCode(RedisTemplate<String, Object> redisTemplate, String verifyCode, String random, boolean ifTrueDelete) {
        Object o = redisTemplate.opsForValue().get(random);
        if (o == null) {
            return false;
        }
        String s = o.toString();
        if (verifyCode != null && verifyCode.equalsIgnoreCase(s)) {
            if (ifTrueDelete) {
                redisTemplate.delete(random);
            }
            return true;
        }
        return false;
    }
}
